# 商品管理
from rest_framework.viewsets import ModelViewSet
from apps.goods.models import SPUSpecification
from rest_framework.permissions import IsAdminUser
from apps.meiduo_admin.utils.pager import MyUserPage
from apps.meiduo_admin.utils.utils import GoodsSpecSerializer
from apps.goods.models import SPUSpecification
from rest_framework.response import Response
from django.http import JsonResponse
from apps.goods.models import SPU, SKU
from apps.meiduo_admin.utils.utils import SKUInfo
from rest_framework.decorators import action
from apps.goods.models import GoodsVisitCount, GoodsCategory


class SpecsView(ModelViewSet):
    # 定义查询集
    queryset = SPUSpecification.objects.all()
    # 定义序列化器
    serializer_class = GoodsSpecSerializer
    # 指定权限
    permission_classes = [IsAdminUser]

    # 指定分页
    pagination_class = MyUserPage
    @action(methods=['get'], detail=False)
    def GetEasySpu(self, request):
        spus = SPU.objects.all()
        spu_list = []
        for s in spus:
            spu_list.append({
                'id': s.id,
                'name': s.name
            })

        return Response(spu_list)


class SkuViewSet(ModelViewSet):
    # 定义查询集
    queryset = SKU.objects.all()
    # 定义序列化器
    serializer_class = SKUInfo
    # 定义分页器
    pagination_class = MyUserPage
    # 定义权限
    permission_classes = [IsAdminUser]

    # 拿到字符串查训数据
    def get_queryset(self):
        keyword = self.request.query_params.get('keyword')

        if keyword is None or keyword == '':
            return self.queryset
        return SKU.objects.filter(name=keyword)

    # 获得三级分类数据
    @action(methods=['get'], detail=False)
    def categories(self, request):

        # 查询三级数据如果一查多为None就说明是三级数据了
        categoriess = GoodsCategory.objects.filter(subs=None)
        categorie_list = []
        for categorie in categoriess:
            categorie_list.append({
                'id': categorie.id,
                'name': categorie.name
            })
        return Response(categorie_list)

